﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using Microsoft.SharePoint.Utilities;

/*
 * Adapted from http://blogs.msdn.com/sgoodyear/archive/2008/06/14/updating-the-docicon-xml-file-with-a-feature.aspx
 */
namespace Community.SharePoint.PdfIcon
{
    public static class PdfIconHelper
    {
        private static string _docIconFilePath;

        private static string DocIconFilePath
        {
            get
            {
                if (_docIconFilePath == null)
                {
                    _docIconFilePath = Path.Combine(
                        SPUtility.GetGenericSetupPath("TEMPLATE\\XML"),
                        "DOCICON.XML");
                }

                return _docIconFilePath;
            }
        }

        public static void Activate()
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(DocIconFilePath);
            XmlNode documentElement = xmlDocument.DocumentElement;
            XmlNode pdfNode = documentElement.SelectSingleNode("ByExtension/Mapping[@Key='pdf']");

            if (pdfNode == null)
            {
                pdfNode = xmlDocument.CreateElement("Mapping");

                pdfNode.Attributes.Append(xmlDocument.CreateAttribute("Key")).Value = "pdf";
                pdfNode.Attributes.Append(xmlDocument.CreateAttribute("Value")).Value = "pdf.gif";

                bool wasAdded = false;

                XmlNode byExtensionNode = documentElement.SelectSingleNode("ByExtension");

                foreach (XmlNode node in byExtensionNode.ChildNodes)
                {
                    if (node.Attributes["Key"].Value.CompareTo("pdf") > 0)
                    {
                        byExtensionNode.InsertBefore(pdfNode, node);
                        wasAdded = true;

                        break;
                    }

                }

                if (!wasAdded)
                {
                    byExtensionNode.AppendChild(pdfNode);
                }

                xmlDocument.Save(DocIconFilePath);
            }
        }

        public static void Deactivate()
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(DocIconFilePath);
            XmlNode documentElement = xmlDocument.DocumentElement;
            XmlNode pdfNode = documentElement.SelectSingleNode("ByExtension/Mapping[@Key='pdf']");

            if (pdfNode != null)
            {
                XmlNode byExtensionNode = documentElement.SelectSingleNode("ByExtension");
                byExtensionNode.RemoveChild(pdfNode);
                xmlDocument.Save(DocIconFilePath);
            }
        }
    }
}
